﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

/*添加一组控件用以调节树的绘制参数。
 * 参数包括递归深度（n）、主干长度（leng）、
 * 右分支长度比（per1）、左分支长度比（per2）、右分支角度（th1）、
 * 左分支角度（th2）、画笔颜色（pen）。*/

namespace CayleyTree
{
    public partial class Form1 : Form
    {
         private Graphics graphics;
        public int th1 { get; set; }//右分支角度
        public int th2 { get; set; }//左分支角度
        public double per1 { get; set; }//右分支长度比
        public double per2 { get; set; }//左分支长度比
        public double leng { get; set; }//主干长度
        public int n { get; set; }//递归深度
        public Pen DrawPen { get; set; }//画笔
        public Form1()
        {
            InitializeComponent();
        }
        public void Form1_Load(object sender,EventArgs e)
        {
           
        }
        private void Run_Click(object sender, EventArgs e)
        {
            th1 = 30;
            th2 = 20;
            per1 = 0.6;
            per2 = 0.7;
            leng = 100;
            n = 10;
            DrawPen = Pens.Black;
            if (graphics == null)
                graphics = this.CreateGraphics();
            n = int.Parse(textBox1.Text);
            leng = double.Parse(textBox2.Text);
            per1 = double.Parse(textBox3.Text);
            per2 = double.Parse(textBox4.Text);
            th1 = int.Parse(textBox5.Text);
            th2 = int.Parse(textBox6.Text);
            if (Pencolor.Text == "Red")
            {
                DrawPen = Pens.Red;
            }
            graphics = this.panel1.CreateGraphics();
            graphics.Clear(panel1.BackColor);
           
            DrawCayleyTree(this.n, panel1.Width/2, panel1.Height-20,this.leng, -Math.PI / 2);

        }
       

        void DrawCayleyTree(int n, double x0, double y0, double leng, double th)
        {
            if (n == 0)
                return;

            double x1 = x0 + leng * Math.Cos(th);
            double y1 = y0 + leng * Math.Sin(th);

            DrawLine(x0, y0, x1, y1);

            DrawCayleyTree(n - 1, x1, y1, per1 * leng, th + th1*Math.PI/180);
            DrawCayleyTree(n - 1, x1, y1, per2 * leng, th - th2*Math.PI/180);
        }

        void DrawLine(double x0, double y0, double x1, double y1)
        {
            graphics.DrawLine( DrawPen,(int)x0, (int)y0, (int)x1, (int)y1);
        

        }


    }
}
